<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能咨询助手</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/11.4.0/styles/github-dark.min.css">
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/marked/4.0.2/marked.min.js"></script>
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/11.4.0/highlight.min.js"></script>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <header class="header">
            <h1>智能咨询助手</h1>
        </header>

        <!-- 主要聊天区域 -->
        <main class="chat-container">
            <div id="chat-messages" class="chat-messages">
                <!-- 欢迎消息 -->
                <div class="welcome-message">
                    <h2>欢迎使用智能咨询助手</h2>
                    <p>您可以在下方输入问题，与AI助手进行咨询。</p>
                    <p>支持多种AI模型，可以随时切换不同的模型。</p>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="chat-input-container">
                <div class="control-options">
                    <div class="model-selector">
                        <select class="model-select" id="modelSelect">
                            {% for model in models %}
                            <option value="{{ model }}" {% if model == current_model.name %}selected{% endif %}>{{ model }}</option>
                            {% endfor %}
                        </select>
                        <span class="model-info" id="modelInfo">
                            {% if current_model %}
                            当前使用: {{ current_model.name }}
                            {% endif %}
                        </span>
                    </div>
                    <label class="toggle-switch" id="deep-thinking-container" style="display: none;">
                        <input type="checkbox" id="deep-thinking-toggle" checked>
                        <span class="toggle-slider"></span>
                        <span class="toggle-label">深度思考</span>
                    </label>
                </div>
                <div class="input-group">
                    <textarea 
                        id="user-input" 
                        placeholder="请输入您的问题..."
                        rows="1"
                    ></textarea>
                    <button id="send-button" type="button">
                        <i class="bi bi-send"></i>
                        <span>发送</span>
                    </button>
                </div>
            </div>
        </main>
    </div>

    <!-- 消息模板 -->
    <template id="user-message-template">
        <div class="message user-message">
            <div class="message-header">
                <div class="avatar user-avatar">我</div>
                <div class="timestamp"></div>
            </div>
            <div class="message-content"></div>
        </div>
    </template>

    <template id="ai-message-template">
        <div class="message ai-message">
            <div class="message-header">
                <div class="avatar ai-avatar"></div>
                <span class="timestamp"></span>
            </div>
            <div class="message-content reasoning">
                <div class="thinking-indicator">
                    <span>思考中</span>
                    <div class="dot"></div>
                    <div class="dot"></div>
                    <div class="dot"></div>
                </div>
                <div class="reasoning-content"></div>
            </div>
            <div class="message-content answer"></div>
        </div>
    </template>

    <template id="loading-template">
        <div class="message ai-message loading">
            <div class="message-header">
                <div class="avatar ai-avatar"></div>
            </div>
            <div class="thinking">
                <span>思考中</span>
                <div class="dot"></div>
                <div class="dot"></div>
                <div class="dot"></div>
            </div>
        </div>
    </template>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 配置marked选项
            marked.setOptions({
                highlight: function(code, lang) {
                    if (lang && hljs.getLanguage(lang)) {
                        return hljs.highlight(code, { language: lang }).value;
                    }
                    return hljs.highlightAuto(code).value;
                },
                breaks: true,
                gfm: true
            });

            // 获取DOM元素
            const chatMessages = document.getElementById('chat-messages');
            const userInput = document.getElementById('user-input');
            const sendButton = document.getElementById('send-button');
            const modelSelect = document.getElementById('modelSelect');
            const modelInfo = document.getElementById('modelInfo');
            
            // 存储对话历史
            const messages = [];
            
            // 自动调整输入框高度
            function adjustTextareaHeight() {
                userInput.style.height = 'auto';
                userInput.style.height = Math.min(userInput.scrollHeight, 200) + 'px';
            }

            // 获取当前时间
            function getCurrentTime() {
                return new Date().toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }

            // 滚动到底部
            function scrollToBottom() {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }

            // 添加用户消息
            function addUserMessage(content) {
                const template = document.getElementById('user-message-template');
                const message = template.content.cloneNode(true);
                
                message.querySelector('.message-content').textContent = content;
                message.querySelector('.timestamp').textContent = getCurrentTime();
                
                chatMessages.appendChild(message);
                scrollToBottom();
            }

            // 更新AI头像显示的函数
            function updateAiAvatars(modelName) {
                const aiAvatars = document.querySelectorAll('.ai-avatar');
                aiAvatars.forEach(avatar => {
                    avatar.textContent = modelName.replace('模型', '');
                });
            }

            // 添加AI消息
            function addAiMessage() {
                const template = document.getElementById('ai-message-template');
                const message = template.content.cloneNode(true);
                
                message.querySelector('.timestamp').textContent = getCurrentTime();
                message.querySelector('.ai-avatar').textContent = modelSelect.value.replace('模型', '');
                
                chatMessages.appendChild(message);
                return chatMessages.lastElementChild;
            }

            // 添加加载动画
            function addLoadingMessage() {
                const existingLoading = document.querySelector('.loading');
                if (existingLoading) {
                    existingLoading.remove();
                }
                
                const template = document.getElementById('loading-template');
                const message = template.content.cloneNode(true);
                message.querySelector('.ai-avatar').textContent = modelSelect.value.replace('模型', '');
                
                chatMessages.appendChild(message);
                scrollToBottom();
            }

            // 添加一个辅助函数来处理内容更新
            function updateMessageContent(container, content) {
                const currentContent = container.getAttribute('data-content') || '';
                const newContent = currentContent + content;
                container.setAttribute('data-content', newContent);
                
                // 立即进行 Markdown 渲染
                container.innerHTML = marked.parse(newContent);
                
                // 高亮代码块
                container.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightBlock(block);
                });
                
                // 滚动到底部
                scrollToBottom();
            }

            // 发送消息
            async function sendMessage() {
                const content = userInput.value.trim();
                if (!content) return;

                // 添加用户消息到界面
                addUserMessage(content);
                
                // 添加到历史记录
                messages.push({
                    role: 'user',
                    content: content,
                    options: {
                        model: modelSelect.value,
                        deep_thinking: document.getElementById('deep-thinking-toggle').checked
                    }
                });

                // 清空输入框并重置高度
                userInput.value = '';
                adjustTextareaHeight();

                // 显示加载动画
                addLoadingMessage();

                try {
                    // 发送请求
                    const response = await fetch('/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            messages: messages,
                            options: {
                                model: modelSelect.value
                            }
                        })
                    });

                    if (!response.ok) {
                        throw new Error('网络请求失败');
                    }

                    // 处理流式响应
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let aiMessage = null;
                    let buffer = '';

                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        buffer += decoder.decode(value, { stream: true });
                        const lines = buffer.split('\n\n');
                        buffer = lines.pop() || '';

                        for (const line of lines) {
                            if (!line.trim() || !line.startsWith('data:')) continue;

                            try {
                                const data = JSON.parse(line.substring(5));

                                switch (data.type) {
                                    case 'start':
                                        // 移除加载动画
                                        const loadingMessage = document.querySelector('.loading');
                                        if (loadingMessage) {
                                            loadingMessage.remove();
                                        }
                                        // 创建新的AI消息
                                        aiMessage = addAiMessage();
                                        break;

                                    case 'reasoning':
                                        if (aiMessage) {
                                            const reasoningContent = aiMessage.querySelector('.reasoning-content');
                                            const thinkingIndicator = aiMessage.querySelector('.thinking-indicator');
                                            const reasoningContainer = aiMessage.querySelector('.message-content.reasoning');
                                            
                                            if (reasoningContent && reasoningContainer) {
                                                // 确保思考过程容器可见
                                                reasoningContainer.style.display = 'block';
                                                
                                                // 显示思考中提示
                                                if (thinkingIndicator) {
                                                    thinkingIndicator.style.display = 'flex';
                                                }
                                                
                                                // 更新并渲染内容
                                                updateMessageContent(reasoningContent, data.content);
                                            }
                                        }
                                        break;

                                    case 'switch_to_answer':
                                        if (aiMessage) {
                                            const thinkingIndicator = aiMessage.querySelector('.thinking-indicator');
                                            if (thinkingIndicator) {
                                                thinkingIndicator.style.display = 'none';
                                            }
                                        }
                                        break;

                                    case 'answer':
                                        if (aiMessage) {
                                            const answerContent = aiMessage.querySelector('.message-content.answer');
                                            if (answerContent) {
                                                // 更新并渲染内容
                                                updateMessageContent(answerContent, data.content);
                                            }
                                        }
                                        break;

                                    case 'error':
                                        if (!aiMessage) {
                                            aiMessage = addAiMessage();
                                        }
                                        const errorContainer = aiMessage.querySelector('.message-content.answer');
                                        if (errorContainer) {
                                            errorContainer.textContent = `错误: ${data.content}`;
                                        }
                                        break;
                                }
                            } catch (error) {
                                console.error('解析响应数据失败:', error);
                            }
                        }
                    }
                } catch (error) {
                    console.error('请求失败:', error);
                    const loadingMessage = document.querySelector('.loading');
                    if (loadingMessage) {
                        const aiMessage = addAiMessage();
                        const errorContainer = aiMessage.querySelector('.message-content.answer');
                        if (errorContainer) {
                            errorContainer.textContent = `发生错误: ${error.message}`;
                        }
                        loadingMessage.remove();
                    }
                }
            }

            // 切换模型
            async function switchModel() {
                try {
                    const response = await fetch('/models/switch', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            model_name: modelSelect.value
                        })
                    });

                    if (!response.ok) {
                        throw new Error('切换模型失败');
                    }

                    const data = await response.json();
                    if (data.success) {
                        modelInfo.textContent = `当前使用: ${data.current_model.name}`;
                        
                        // 控制深度思考选项的显示
                        const deepThinkingContainer = document.getElementById('deep-thinking-container');
                        const modelName = data.current_model.name.toLowerCase();
                        if (modelName.includes('百炼') || modelName.includes('蓝源')) {
                            deepThinkingContainer.style.display = 'inline-flex';
                        } else {
                            deepThinkingContainer.style.display = 'none';
                        }
                    }
                } catch (error) {
                    console.error('切换模型失败:', error);
                }
            }

            // 事件监听器
            userInput.addEventListener('input', adjustTextareaHeight);
            
            userInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            sendButton.addEventListener('click', sendMessage);
            modelSelect.addEventListener('change', switchModel);

            // 初始化时也要检查是否显示深度思考选项
            const initialModelName = modelSelect.value.toLowerCase();
            const deepThinkingContainer = document.getElementById('deep-thinking-container');
            if (initialModelName.includes('百炼') || initialModelName.includes('蓝源')) {
                deepThinkingContainer.style.display = 'inline-flex';
            } else {
                deepThinkingContainer.style.display = 'none';
            }

            // 初始化
            adjustTextareaHeight();
        });
    </script>
</body>
</html> 